<?php

namespace app\common\model\user;

use addons\cms\model\Notice;
use app\common\model\User;
use think\Model;


class Level extends Model
{

    

    

    // 表名
    protected $name = 'user_level';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'level_text'
    ];
    

    

    public function level()
    {
        return [
            '1' => '一级',
            '2' => '二级',
            '3' => '三级',
            '4' => '四级',
            '5' => '五级',
            '6' => '六级',
            '7' => '七级',
            '8' => '八级',
            '9' => '九级',
            '10' => '十级',
        ];
    }
    public function getImageAttr($value, $data)
    {
        $value = $value ? $value : '';
        return cdnurl($value);
    }


    public function getLevelTextAttr($value, $data)
    {

        $value = $value ? $value : (isset($data['level']) ? $data['level'] : '');
        $list = $this->level();
        return isset($list[$value]) ? $list[$value] : '';
    }

    /**
     * @param $user_id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 会员升级
     */
    public static function UserUpdate($user_id)
    {
        $user = User::where('id',$user_id)->find();

        $level_list = self::order('level asc')->select();
        $user_level_info = self::where('id',$user['level_id'])->find();
        $level_info = [];
        foreach ($level_list as $key => $value){
            if ($user_level_info['level'] < $value['level']){
                $level_info = $value;
                break;
            }
        }
        if (!$level_info){
            return false;
        }
        //还存在比会员等级高的等级
        if ($user->sign_activity >= $level_info['up_sign_activity']){
            \app\common\model\User::where('id',$user_id)->update(['level_id' => $level_info['id']]);
            if ($level_info['up_score'] > 0){
                Notice::create([
                    'type' => 'user_update_level',
                    'title' => '系统消息',
                    'user_id' => $user_id,
                    'content' => '升级成为'.$level_info['name'].'，获得积分奖励：'.$level_info['up_score'],
                    'createtime' => time()
                ]);
                User::score($level_info['up_score'],'user_update_level', $user_id, 0,'升级奖励');
            }
            return true;
        }
        return false;
    }
}
